/**
 * 搜索头部组件 JavaScript 功能
 * 包含搜索、翻转效果、自动完成等功能
 */

// 搜索URL配置
var searchURL = {
    // 搜索引擎
    "google": {
        "search" : "https://www.google.com/#newwindow=1&safe=strict&q=%keyword%",
        "home" : "https://www.google.com"
    },
    "baidu": {
        "search" : "https://www.baidu.com/s?wd=%keyword%",
        "home" : "https://www.baidu.com"
    },
    "bing": {
        "search" : "https://www.bing.com/search?q=%keyword%",
        "home" : "https://www.bing.com"
    },
    "sogou": {
        "search" : "https://www.sogou.com/web?query=%keyword%",
        "home" : "https://www.sogou.com"
    },
    "360": {
        "search" : "https://www.so.com/s?ie=utf-8&src=360chrome_toolbar_search&q=%keyword%",
        "home" : "https://www.so.com"
    },
    
    // 社交网络
    "sinaweibo": {
        "search" : "https://s.weibo.com/weibo/%keyword%",
        "home" : "https://weibo.com"
    },
    "zhihu": {
        "search" : "http://www.zhihu.com/search?q=%keyword%",
        "home" : "http://www.zhihu.com"
    },
    
    // 购物
    "taobao": {
        "search" : "https://s.taobao.com/search?q=%keyword%",
        "home" : "https://www.taobao.com"
    },
    "tmall": {
        "search" : "https://list.tmall.com/search_product.htm?q=%keyword%",
        "home" : "https://www.tmall.com"
    },
    "jd": {
        "search" : "https://search.jd.com/Search?keyword=%keyword%",
        "home" : "https://www.jd.com"
    },
    
    // 视频
    "bilibili": {
        "search" : "https://search.bilibili.com/all?keyword=%keyword%",
        "home" : "https://www.bilibili.com"
    },
    "youku": {
        "search" : "https://so.youku.com/search_video/q_%keyword%",
        "home" : "https://www.youku.com"
    },
    "iqiyi": {
        "search" : "https://so.iqiyi.com/so/q_%keyword%",
        "home" : "https://www.iqiyi.com"
    },
    
    // 音乐
    "wangyi": {
        "search" : "https://music.163.com/#/search/m/?s=%keyword%",
        "home" : "https://music.163.com"
    },
    "qqy": {
        "search" : "https://y.qq.com/portal/search.html#page=1&searchid=1&remoteplace=txt.yqq.top&t=song&w=%keyword%",
        "home" : "https://y.qq.com"
    }
};

// 自动完成功能变量
var changeStr = '';   
var timeoutId;
var highlightindex = -1;

/**
 * 搜索头部组件初始化
 */
function initSearchHeader() {
    // 页面加载完成后聚焦搜索框
    $(document).ready(function(){  
        document.getElementById('B1').focus();  
    });

    // 绑定翻转效果
    bindFlipEffects();
    
    // 绑定键盘事件
    bindKeyboardEvents();
    
    // 绑定其他事件
    bindOtherEvents();
}

/**
 * 绑定翻转效果
 */
function bindFlipEffects() {
    // Logo翻转效果
    $('.flip-container-OK').click(function() {
        $(this).toggleClass('backimgOK');
    });
    
    // 搜索引擎切换翻转效果
    $('.flip-container').click(function() {
        $(this).toggleClass('backimg');
    });
}

/**
 * 绑定其他事件
 */
function bindOtherEvents() {
    // 点击页面其他地方隐藏自动完成
    $(document).click(function(e) {
        if (!$(e.target).closest('.sousuokuang, #auto').length) {
            $("#auto").hide();
            highlightindex = -1;
        }
    });
    
    // 搜索框失去焦点时延迟隐藏自动完成
    $('#B1').blur(function() {
        setTimeout(function() {
            $("#auto").hide();
            highlightindex = -1;
        }, 200);
    });
}

/**
 * 搜索功能
 * @param {Element} sender - 触发搜索的元素
 */
function search(sender) {
    var keyword = $("#B1").val();
    if(keyword == null || keyword == "") {
        alert("请输入搜索关键词");
        return;
    }
    
    var searchId = sender.id;
    if(searchURL[searchId]) {
        var url = searchURL[searchId].search.replace('%keyword%', encodeURIComponent(keyword));
        window.open(url, '_blank');
    }
}

/**
 * 判断搜索引擎并执行搜索
 */
function judge() {
    var keyword = $("#B1").val();
    if(keyword == null || keyword == "") {
        return;
    }
    
    // 检查当前选择的搜索引擎
    var isGoogle = $('.flip-container').hasClass('backimg');
    var searchEngine = isGoogle ? 'google' : 'baidu';
    
    var url = searchURL[searchEngine].search.replace('%keyword%', encodeURIComponent(keyword));
    window.open(url, '_blank');
}

/**
 * 获取搜索建议
 */
function FillUrls() {
    var strdomin = $("#B1").val();
    
    if (strdomin == null || strdomin == "") {
        $("#auto").empty();
        $("#auto").hide();
        return;
    }

    // 如果与上次请求相同则返回
    if (changeStr == strdomin) {
        return;
    }

    changeStr = strdomin;

    var qsData = { 
        'wd': strdomin, 
        'p': '3', 
        'cb': 'ShowDiv', 
        't': new Date().getMilliseconds().toString() 
    };
    
    $.ajax({
        async: true,
        url: "https://suggestion.baidu.com/su",
        type: "GET",
        dataType: 'jsonp',
        jsonp: 'jsoncallback',
        data: qsData,
        timeout: 5000,
        success: function (json) {
            // 成功回调在ShowDiv中处理
        },
        error: function (xhr) {
            console.log("获取搜索建议失败");
        }
    });
}

/**
 * 显示搜索建议
 * @param {Object} strurls - 百度返回的搜索建议数据
 */
function ShowDiv(strurls) {
    autoDisplay(strurls);
}

/**
 * 自动显示建议
 * @param {Object} autoStr - 搜索建议数据
 */
function autoDisplay(autoStr) {
    var Info = autoStr['s'];
    var autoNode = $("#auto");
    
    if (!Info || Info.length == 0) {
        autoNode.hide();
        return false;
    }
    
    autoNode.empty();
    
    for (var i = 0; i < Math.min(Info.length, 8); i++) {
        var wordNode = Info[i];
        var newDivNode = $("<div>").attr("id", i);
        newDivNode.attr("style", "display:block;width:100%;font:16px/25px arial;padding:8px 15px;cursor: pointer;margin:5px 0;box-shadow: 0 2px 8px rgba(0,0,0,0.1);-webkit-box-shadow:0 2px 8px rgba(0,0,0,0.1);border-radius:20px;background:rgba(255,255,255,1) !important;color:rgba(0,0,0,1);transition:all 0.3s ease;position:relative;z-index:98 !important;border:1px solid rgba(0,0,0,0.05);");
        newDivNode.html(wordNode).appendTo(autoNode);
        
        // 鼠标交互事件
        newDivNode.mouseover(function () {
            if (highlightindex != -1) {
                autoNode.children("div").eq(highlightindex).css({
                    "background-color": "rgba(255,255,255,1)",
                    "color": "rgba(0,0,0,1)",
                    "box-shadow": "0 0 15px rgba(78,70,70,0.08)"
                });
            }
            
            highlightindex = $(this).attr("id");
            $(this).css({
                "background-color": "rgba(7,205,250,0.60)",
                "color": "rgba(255,255,255,1)",
                "box-shadow": "0 0 15px rgba(7,205,250,0.4)"
            });
        });
        
        newDivNode.mouseout(function () {
            if (highlightindex != -1) {
                autoNode.children("div").eq(highlightindex).css({
                    "background-color": "rgba(255,255,255,1)",
                    "color": "rgba(0,0,0,1)",
                    "box-shadow": "0 0 15px rgba(78,70,70,0.08)"
                });
            }
        });

        newDivNode.click(function () {
            var comText = $(this).text();
            $("#auto").hide();
            highlightindex = -1;
            $("#B1").val(comText);
            judge();
        });
    }
    
    if (Info.length > 0) {
        autoNode.show();
    } else {
        autoNode.hide();
        highlightindex = -1;
    }
}

/**
 * 绑定键盘事件
 */
function bindKeyboardEvents() {
    $("#B1").keyup(function (event) {
        var myEvent = event || window.event;
        var keyCode = myEvent.keyCode;

        // 字母、数字、退格、删除、空格等键触发搜索建议
        if ((keyCode >= 65 && keyCode <= 90) || 
            (keyCode >= 48 && keyCode <= 57) || 
            (keyCode >= 96 && keyCode <= 111) || 
            (keyCode >= 186 && keyCode <= 222) || 
            keyCode == 8 || keyCode == 46 || keyCode == 32) {
            
            // 延迟请求，避免频繁请求
            clearTimeout(timeoutId);
            timeoutId = setTimeout(function() {
                FillUrls();
            }, 300);
            
            if (highlightindex != -1) {
                highlightindex = -1;
            }
        }
        else if (keyCode == 38 || keyCode == 40) {
            // 上下键选择建议
            handleArrowKeys(keyCode);
        } 
        else if (keyCode == 13) {
            // 回车键
            handleEnterKey();
        } 
        else if (keyCode == 27) {
            // ESC键
            handleEscapeKey();
        }
    });
}

/**
 * 处理上下箭头键
 * @param {number} keyCode - 键码
 */
function handleArrowKeys(keyCode) {
    var autoNodes = $("#auto").children("div");
    
    if (autoNodes.length == 0) return;
    
    if (keyCode == 38) {  // 向上
        if (highlightindex != -1) {
            autoNodes.eq(highlightindex).css({
                "background-color": "rgba(255,255,255,1)",
                "color": "rgba(0,0,0,1)",
                "box-shadow": "0 0 15px rgba(78,70,70,0.08)"
            });
            highlightindex--;
        } else {
            highlightindex = autoNodes.length - 1;
        }
        if (highlightindex == -1) {
            highlightindex = autoNodes.length - 1;
        }
    }
    
    if (keyCode == 40) {  // 向下
        if (highlightindex != -1) {
            autoNodes.eq(highlightindex).css({
                "background-color": "rgba(255,255,255,1)",
                "color": "rgba(0,0,0,1)",
                "box-shadow": "0 0 15px rgba(78,70,70,0.08)"
            });
        }
        highlightindex++;
        if (highlightindex == autoNodes.length) {
            highlightindex = 0;
        }
    }
    
    // 高亮当前选中项
    autoNodes.eq(highlightindex).css({
        "background-color": "rgba(7,205,250,0.60)",
        "color": "rgba(255,255,255,1)",
        "box-shadow": "0 0 15px rgba(7,205,250,0.4)"
    });
    
    var comText = autoNodes.eq(highlightindex).text();
    $("#B1").val(comText);
}

/**
 * 处理回车键
 */
function handleEnterKey() {
    if (highlightindex != -1) {
        var comText = $("#auto").children("div").eq(highlightindex).text();
        $("#auto").hide();
        highlightindex = -1;
        $("#B1").val(comText);
        judge();
    } else {
        $("#auto").hide();
        judge();
    }
}

/**
 * 处理ESC键
 */
function handleEscapeKey() {
    if ($("#auto").is(":visible")) {
        $("#auto").hide();
        highlightindex = -1;
    }
}

/**
 * 设置搜索引擎
 * @param {string} engine - 搜索引擎名称 ('baidu' 或 'google')
 */
function setSearchEngine(engine) {
    var $container = $('.flip-container');
    if (engine === 'google') {
        $container.addClass('backimg');
    } else {
        $container.removeClass('backimg');
    }
}

/**
 * 获取当前搜索引擎
 * @returns {string} 当前搜索引擎名称
 */
function getCurrentSearchEngine() {
    var isGoogle = $('.flip-container').hasClass('backimg');
    return isGoogle ? 'google' : 'baidu';
}

/**
 * 清空搜索框
 */
function clearSearchInput() {
    $("#B1").val('');
    $("#auto").hide();
    highlightindex = -1;
    $("#B1").focus();
}

/**
 * 设置搜索关键词
 * @param {string} keyword - 搜索关键词
 */
function setSearchKeyword(keyword) {
    $("#B1").val(keyword);
    $("#B1").focus();
}

// 导出函数供外部使用
window.SearchHeader = {
    init: initSearchHeader,
    search: search,
    judge: judge,
    setSearchEngine: setSearchEngine,
    getCurrentSearchEngine: getCurrentSearchEngine,
    clearSearchInput: clearSearchInput,
    setSearchKeyword: setSearchKeyword
};

// 自动初始化（如果jQuery已加载）
$(document).ready(function() {
    if (typeof $ !== 'undefined') {
        initSearchHeader();
    }
});